<?php

/*
 * мепер, отвечающий за работу с таблицей юзеров
 */

class Model_UserMapper {
    public static function setAva($userId, $photoId){$_SESSION['query']=0;
        $dbConnection = Control_DbConnection::getConnection();
        $query = "UPDATE user SET ava=(SELECT pathToMini FROM img WHERE id='".$photoId."') WHERE id='".$userId."';";
        $dbConnection->dbQuery($query);
        if($dbConnection->getRes()){$_SESSION['query']++;
           return true; 
        } else {
            View_View::setError(Model_Error::getDbQueryError());
            return false;
        }
    }
    public static function getCurrentUser($id){
        if($_SESSION['authUserId']==$id){
            return true;
        }else{
            return false;
        }
    }
    public static function getAllUsers($data) {$_SESSION['query']=0;
        $dbConnection = Control_DbConnection::getConnection();
        $query = "SELECT COUNT(*) FROM (SELECT id, name, sex, age FROM user WHERE name LIKE '%" . $data['name'] . "%' AND sex LIKE 
                 '%" . $data['sex'] . "%' AND age LIKE '%" . $data['age'] . "%') AS Array";
        $dbConnection->dbQuery($query);
        if ($dbConnection->getRes()) {$_SESSION['query']++;
            $row = implode(mysql_fetch_array($dbConnection->getRes(), MYSQL_NUM));
        }return $row;
    }

    public static function getTenUsersBy($data) {$_SESSION['query']=0;
        $dbConnection = Control_DbConnection::getConnection();
        if (!isset($data['sex'])) {
            $data['sex'] = '';
            $_SESSION['searchProperties']['sex'] = '';
        }
        if ($data['page'] == 'route') {
            $query = "SELECT id, name, sex, age, ava FROM user WHERE name LIKE '%" . $data['name'] . "%' AND sex LIKE 
                 '%" . $data['sex'] . "%' AND age LIKE '%" . $data['age'] . "%' LIMIT 0, 10;";
        } else if ($data['page'] == '1') {
            $query = "SELECT id, name, sex, age, ava FROM user WHERE name LIKE '%" . $_SESSION['searchProperties']['name'] . "%' AND sex LIKE 
                 '%" . $_SESSION['searchProperties']['sex'] . "%' AND age LIKE '%" . $_SESSION['searchProperties']['age'] . "%' LIMIT 0, 10;";
        } else {
            $firstPage = ($data['page'] - 1) * 10;
            $lastpage = $data['page'] * 10 - 1;
            $query = "SELECT id, name, sex, age, ava FROM user WHERE name LIKE '%" . $_SESSION['searchProperties']['name'] . "%' AND sex LIKE 
                 '%" . $_SESSION['searchProperties']['sex'] . "%' AND age LIKE '%" . $_SESSION['searchProperties']['age'] . "%' LIMIT $firstPage, $lastPage;";
        }


        $dbConnection->dbQuery($query);
        if ($dbConnection->getRes()) {$_SESSION['query']++;
            while ($row = mysql_fetch_array($dbConnection->getRes(), MYSQLI_ASSOC)) {
                $obj[] = new Model_user($row);
            }
            return $obj;
        } else {
            View_View::setError(Model_Error::getDbQueryError());
            return false;
        }
    }

    public static function getThisUser($id) {$_SESSION['query']=0;
        $dbConnection = Control_DbConnection::getConnection();
        $query = "SELECT id, name, sex, age, ava FROM user WHERE id='" . $id . "';";
        $dbConnection->dbQuery($query);
        if ($dbConnection->getRes()) {
            while ($row = mysql_fetch_array($dbConnection->getRes(), MYSQLI_ASSOC)) {
                $obj = $row;
            }
            return new Model_User($obj);
        } else {
            View_View::setError(Model_Error::getDbQueryError());
            return false;
        }
    }

    public static function authUser($logPas) {$_SESSION['query']=0;
        $dbConnection = Control_DbConnection::getConnection();
        $logPas = Control_Validator::authValid($logPas);
        if (is_array($logPas)) { // проверяем валидность введенных логина и пароля
            $query = "SELECT id, name FROM user WHERE login='" . $logPas['log'] . "' AND password='" . $logPas['pas'] . "';";
            $dbConnection->dbQuery($query);
            if ($dbConnection->getRes()) {$_SESSION['query']++;
                while ($row = mysql_fetch_array($dbConnection->getRes(), MYSQL_ASSOC)) {
                    $obj = $row;
                }
                return $obj;
            } else { // если не прошел запрос
                View_View::setError(Model_Error::getDbQueryError());
                return false;
            }
        } else { // если введенные логин и пароль не валидны
            View_View::setError(Control_Validator::getError());
            return false;
        }
    }

    public static function saveUser($userModel) {$_SESSION['query']=0;
    
        $dbConnection = Control_DbConnection::getConnection();
        if (!is_object($userModel)) {
            $userModel = Control_Validator::updateValid($userModel);
            if (!is_array($userModel)){ // если валидация не пройдена
                View_View::setError(Control_Validator::getError());
                return false;
            } else {
                $query = "UPDATE user SET name='".$userModel['name']."', age='".$userModel['age']."' WHERE id='".$userModel['id']."';";
                $dbConnection->dbQuery($query);
                if($dbConnection->getRes()){$_SESSION['query']++;
                    return true;
                } else {
                    View_View::setError(Model_Error::getDbQueryError());
                    return false;
                }
            }
            
        } else {
            
            $userLogin = Control_Validator::logValid($userModel->getUserLog());
            
            if (null == $userLogin) { //проверяем валидность введенного логина
                $query = "SELECT id FROM user WHERE login='" . $userModel->getUserLog() . "';";
                
                $dbConnection->dbQuery($query);
                if ($dbConnection->getRes()) {$_SESSION['query']++;
                    $row = mysql_fetch_array($dbConnection->getRes(), MYSQL_NUM);
                    if (!$row) { // проверяем есть ли совпадения введенного логина с бд
                        $userModel = Control_Validator::regValid($userModel);
                        if (is_object($userModel)) { // проверяем валидность заполненых полей
                            $query = "INSERT INTO user (name, login, password, sex, age) 
                        VALUES ('" . $userModel->getUserName() . "', '" . $userModel->getUserLog() .
                                    "', '" . $userModel->getUserPas() . "', '" . $userModel->getUserSex() . "', 
                        '" . $userModel->getUserAge() . "');";
                            $dbConnection->dbQuery($query);
                            if ($dbConnection->getRes()) {
                                $id = mysql_insert_id();
                                mkdir("./img/$id");
                                mkdir("./img/$id/thumb");
                                return true;
                                
                            } else {//если не прошел запрос
                                View_View::setError(Model_Error::getDbQueryError());
                                return false;
                            }
                        } else {//если валидатор вернул ошибку при проверке полей
                            View_View::setError(Control_Validator::getError());
                            return false;
                        }
                    } else { //если введенный юзером логин уже есть в бд
                        View_View::setError(Model_Error::getLoginError());
                        return false;
                    }
                } else { //если не удался запрос на выборку id юзера по введенному логину
                    View_View::setError(Model_Error::getDbQueryError());
                    return false;
                }
            } else { //если введенный логин не валиден
                View_View::setError($userLogin);
                return false;
            }
        }
    }

}

